package TheadConsumerAndProducerTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenjunjie
 * @since 2018-02-11
 */
public class ConditionDemo1 {
    private static  ReentrantLock lock = new ReentrantLock();
    private static Condition condition_a = lock.newCondition();
    private static Condition condition_b = lock.newCondition();
    private static Condition condition_c = lock.newCondition();
    private static int flag = 1; //核心点

    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run(){
                lock.lock();
                while(flag != 1){
                    try {
                        condition_a.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                condition_b.signalAll();
                System.out.print("A");
                flag = 2;
                lock.unlock();
            }
        };

        Thread t2 = new Thread(){
            @Override
            public void run(){
                lock.lock();
                while (flag != 2){
                    try {
                        condition_b.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                condition_c.signalAll();
                System.out.print("B");
                flag = 3;

                lock.unlock();
            }
        };

        Thread t3 = new Thread(){
            @Override
            public void run(){
                lock.lock();
                while(flag != 3){
                    try {
                        condition_c.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                condition_a.signalAll();
                System.out.print("C");
                flag = 1;
                lock.unlock();
            }
        };

        Thread[] aTheadArray = new Thread[5];
        Thread[] bTheadArray = new Thread[5];
        Thread[] cTheadArray = new Thread[5];
        for(int i=0;i<5;i++){
            aTheadArray[i] = new Thread(t1);
            bTheadArray[i] = new Thread(t2);
            cTheadArray[i] = new Thread(t3);

            aTheadArray[i].start();
            bTheadArray[i].start();
            cTheadArray[i].start();

        }
    }

}
